from django.db.models import Avg, Count, Max, Min, Sum, F, Q
from django.http import HttpResponse
from django.views.decorators.http import require_http_methods

from front.models import Book, Author

# Create your views here.

app_name = "front"


def test_avg(request):
    # result = Book.objects.aggregate(Avg('price'))
    result = Book.objects.aggregate(book_price=Avg('price'))
    print(result)
    return HttpResponse("test_avg")


def test_count(request):
    result = Book.objects.aggregate(book_count=Count('id'))
    print(result)
    return HttpResponse("test_count")


def test_max_min(request):
    result = Author.objects.aggregate(age_max=Max('age'), age_min=Min('age'))
    print(result)
    return HttpResponse("test_max_min")


def test_sum(request):
    result = Book.objects.annotate(total=Sum("bookorder__price")).values('name', 'total')
    print(result)
    return HttpResponse("test_sum")


@require_http_methods(["GET"])
def test_f(request):
    # 把所有作者的年龄+1岁,F表达式是加标记
    Author.objects.update(age=F('age') + 1)
    return HttpResponse("test_F")


@require_http_methods(['GET', 'POST'])
def test_q(request):
    # 查找图书总页数小于等于1000页，或者评分小于4.9的图书，Q表达式是一个条件表达式
    books = Book.objects.filter(Q(pages__lte=1000) | Q(rating__lt=4.9))
    for book in books:
        print(book.name)
    return HttpResponse("test_Q")


def add_cookie(request):
    response = HttpResponse("add_cookie")
    max_age = 60 * 60 * 24
    response.set_cookie("username", "haichenyi", max_age=max_age)
    return response


def delete_cookie(request):
    response = HttpResponse("delete_cookie")
    response.delete_cookie("username")
    return response


def get_cookie(request):
    cookie = request.COOKIES.get("username")
    print(cookie)
    cookie_items = request.COOKIES.items()
    for (key, value) in cookie_items:
        print(key, value)
    response = HttpResponse("get_cookie")
    return response

def add_session(request):
    request.session["username"] = "haichenyi"
    # 不设置过期时间，默认2周
    request.session.set_expiry(60 * 60 * 24)
    response = HttpResponse("add_session")
    return response

def get_session(request):
    username = request.session.get("username")
    print(username)
    response = HttpResponse("get_session")
    return response
